import { LLMAdapter, ModelInfo, ValidationResult, ValidationErrorCode } from '../../types/index';

export class AnthropicAdapter implements LLMAdapter {
  private readonly timeout = 10000; // 10秒超时

  async fetchModels(baseURL = 'https://api.anthropic.com/v1', apiKey?: string): Promise<ModelInfo[]> {
    // Anthropic 没有公开的模型列表API，返回静态列表
    // 但保留baseURL参数以便未来扩展
    console.log('AnthropicAdapter: Using baseURL:', baseURL);
    return this.getStaticModels();
  }

  async validateApiKey(apiKey: string, baseURL = 'https://api.anthropic.com/v1'): Promise<ValidationResult> {
    if (!apiKey || !apiKey.trim()) {
      return {
        isValid: false,
        error: {
          code: ValidationErrorCode.INVALID_API_KEY,
          message: 'API Key 不能为空',
          suggestion: '请输入有效的 Anthropic API Key'
        }
      };
    }

    try {
      // 使用轻量级请求测试API Key
      const testPayload = {
        model: 'claude-3-haiku-20240307',
        messages: [{ role: 'user', content: 'test' }],
        max_tokens: 1
      };

      const response = await this.makeRequest(`${baseURL}/messages`, {
        method: 'POST',
        headers: {
          'x-api-key': apiKey,
          'Content-Type': 'application/json',
          'anthropic-version': '2023-06-01'
        },
        body: JSON.stringify(testPayload),
      });

      if (response.ok) {
        const data = await response.json();
        return {
          isValid: true,
          metadata: {
            model: data.model,
            usage: data.usage
          }
        };
      } else {
        const errorData = await response.json().catch(() => ({}));
        return this.handleErrorResponse(response.status, errorData);
      }
    } catch (error) {
      return this.handleNetworkError(error);
    }
  }

  private async makeRequest(url: string, options: RequestInit): Promise<Response> {
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), this.timeout);

    try {
      const response = await fetch(url, {
        ...options,
        signal: controller.signal,
      });
      clearTimeout(timeoutId);
      return response;
    } catch (error) {
      clearTimeout(timeoutId);
      throw error;
    }
  }

  private getStaticModels(): ModelInfo[] {
    return [
      {
        id: 'claude-3-5-sonnet-20241022',
        name: 'Claude 3.5 Sonnet',
        provider: 'anthropic',
        description: 'Most intelligent model with enhanced coding and analysis',
        contextLength: 200000,
        capabilities: ['text', 'vision', 'advanced-reasoning', 'coding'],
      },
      {
        id: 'claude-3-5-haiku-20241022',
        name: 'Claude 3.5 Haiku',
        provider: 'anthropic',
        description: 'Fastest model for everyday tasks',
        contextLength: 200000,
        capabilities: ['text', 'vision'],
      },
      {
        id: 'claude-3-opus-20240229',
        name: 'Claude 3 Opus',
        provider: 'anthropic',
        description: 'Most powerful model for complex tasks',
        contextLength: 200000,
        capabilities: ['text', 'vision', 'advanced-reasoning'],
      },
      {
        id: 'claude-3-sonnet-20240229',
        name: 'Claude 3 Sonnet',
        provider: 'anthropic',
        description: 'Balanced model for most use cases',
        contextLength: 200000,
        capabilities: ['text', 'vision'],
      },
      {
        id: 'claude-3-haiku-20240307',
        name: 'Claude 3 Haiku',
        provider: 'anthropic',
        description: 'Fast and cost-effective model',
        contextLength: 200000,
        capabilities: ['text', 'vision'],
      },
    ];
  }

  private handleErrorResponse(status: number, errorData: any): ValidationResult {
    switch (status) {
      case 401:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.INVALID_API_KEY,
            message: 'API Key 无效或已过期',
            suggestion: '请检查 API Key 是否正确，并确认账户状态正常'
          }
        };
      case 403:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.INSUFFICIENT_PERMISSIONS,
            message: '权限不足或账户被限制',
            suggestion: '请检查账户状态和 API 使用权限'
          }
        };
      case 429:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.RATE_LIMITED,
            message: '请求频率过高',
            suggestion: '请降低请求频率或升级账户计划'
          }
        };
      case 500:
      case 502:
      case 503:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.SERVER_ERROR,
            message: 'Anthropic 服务器错误',
            suggestion: '请稍后重试'
          }
        };
      default:
        return {
          isValid: false,
          error: {
            code: ValidationErrorCode.UNKNOWN_ERROR,
            message: errorData.error?.message || '未知错误',
            suggestion: '请检查配置并重试'
          }
        };
    }
  }

  private handleNetworkError(error: any): ValidationResult {
    if (error.name === 'AbortError') {
      return {
        isValid: false,
        error: {
          code: ValidationErrorCode.TIMEOUT,
          message: '请求超时',
          suggestion: '请检查网络连接或稍后重试'
        }
      };
    }

    return {
      isValid: false,
      error: {
        code: ValidationErrorCode.NETWORK_ERROR,
        message: '网络连接错误',
        suggestion: '请检查网络连接并重试'
      }
    };
  }
}